package com.dc.web.controller;


import com.dc.constant.MessageConstant;
import com.dc.dao.*;
import com.dc.entity.*;
import com.dc.exception.ServiceException;
import com.dc.model.AjaxResult;
import com.dc.model.WorkflowListBody;
import com.dc.model.WorkflowPowerBody;
import com.dc.service.CalibrationService;
import com.dc.service.HttpService2;
import com.dc.service.dto.electronic.HttpGetPowerReturnNewBody;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

@Api(tags = "8-单船工序-超水除锈")
@RequestMapping("/api/workflow_water_clean")
@RestController
public class WorkflowWaterCleanController {

    @Resource
    WorkflowWaterCleanDao workflowWaterCleanDao;

    @Resource
    WorkflowWaterCleanChildDao workflowWaterCleanChildDao;

    @Resource
    ShipRepairDao shipRepairDao;

    @Resource
    ShipDao shipDao;

    @Resource
    CalibrationService calibrationService;

    @Resource
    HttpService2 httpService2;

    @GetMapping("/list")
    public AjaxResult list(WorkflowListBody body) {

        Integer pageNumber = body.getPageNumber();
        pageNumber = ObjectUtils.defaultIfNull(pageNumber, 1);
        Integer pageSize = body.getPageSize();
        pageSize = ObjectUtils.defaultIfNull(pageSize, 20);

        PageRequest pageRequest = PageRequest.of(pageNumber - 1, pageSize);

        Long repairId = body.getRepairId();     // 维修工单id

        Optional<ShipRepairEntity> optionalShipRepair = shipRepairDao.findById(repairId);
        if(!optionalShipRepair.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_SHIP_REPAIR_MISSING);
        }

        ShipRepairEntity shipRepairEntity = optionalShipRepair.get();

        Long shipId = shipRepairEntity.getShipId();
        Optional<ShipEntity> optionalShip = shipDao.findById(shipId);
        if(!optionalShip.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_SHIP_MISSING);
        }

        ShipEntity shipEntity = optionalShip.get();

        Page<WorkflowWaterCleanEntity> resultList = workflowWaterCleanDao.findByShipRepairEntity(shipRepairEntity, pageRequest);

        resultList.getContent().forEach(t -> {
            dynamicCalc(t, shipEntity, shipRepairEntity);
        });

        return AjaxResult.success(resultList);
    }

    @GetMapping("/{id}")
    public AjaxResult show(@PathVariable("id") Long id) {

        Optional<WorkflowWaterCleanEntity> optional = workflowWaterCleanDao.findById(id);
        if(!optional.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_WORK_FLOW_MISSING);
        }

        WorkflowWaterCleanEntity shipOilEntity = optional.get();

        ShipRepairEntity shipRepairEntity = shipOilEntity.getShipRepairEntity();

        Long shipId = shipRepairEntity.getShipId();
        Optional<ShipEntity> optionalShip = shipDao.findById(shipId);

        if(!optionalShip.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_SHIP_MISSING);
        }

        ShipEntity shipEntity = optionalShip.get();

        dynamicCalc(shipOilEntity, shipEntity, shipRepairEntity);

        return AjaxResult.success(shipOilEntity);
    }


    //  shipRepairId   weight   shipWeight    submit_time
    @PostMapping()
    public AjaxResult add(@RequestHeader HttpHeaders httpHeaders, @RequestBody WorkflowWaterCleanEntity entity) {

        entity.setId(null);

        Long shipRepairId = entity.getShipRepairId();
        Optional<ShipRepairEntity> optionalShipRepair = shipRepairDao.findById(shipRepairId);
        if(!optionalShipRepair.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_SHIP_REPAIR_MISSING);
        }

        ShipRepairEntity shipRepairEntity = optionalShipRepair.get();

        Long shipId = shipRepairEntity.getShipId();
        Optional<ShipEntity> optionalShip = shipDao.findById(shipId);
        if(!optionalShip.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_SHIP_MISSING);
        }

        ShipEntity shipEntity = optionalShip.get();

        entity.setShipRepairEntity(shipRepairEntity);
        entity.setSubmitTime(new Date());

        WorkflowWaterCleanEntity save = workflowWaterCleanDao.save(entity);

        dynamicCalc(save, shipEntity, shipRepairEntity);

        return AjaxResult.success(save);
    }

    @PutMapping("/{id}")
    public AjaxResult update(@PathVariable("id") Long id, @RequestBody WorkflowWaterCleanEntity entity) {

        Optional<WorkflowWaterCleanEntity> optionalPaintHouse = workflowWaterCleanDao.findById(id);
        if(!optionalPaintHouse.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_WORK_FLOW_MISSING);
        }

        WorkflowWaterCleanEntity houseEntity = optionalPaintHouse.get();

        ShipRepairEntity shipRepairEntity = houseEntity.getShipRepairEntity();

        Long shipId = shipRepairEntity.getShipId();
        Optional<ShipEntity> optionalShip = shipDao.findById(shipId);
        if(!optionalShip.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_SHIP_MISSING);
        }

        ShipEntity shipEntity = optionalShip.get();

        //////////////////////// 设置字段
        houseEntity.setType(entity.getType());
        houseEntity.setArea(entity.getArea());
        houseEntity.setRoom(entity.getRoom());
        houseEntity.setSubmitTime(new Date());

        WorkflowWaterCleanEntity save = workflowWaterCleanDao.save(houseEntity);

        dynamicCalc(save, shipEntity, shipRepairEntity);

        return AjaxResult.success(save);
    }

    @DeleteMapping("/{id}")
    public AjaxResult delete(@PathVariable("id") Long id) {

        workflowWaterCleanDao.deleteById(id);

        return AjaxResult.success();
    }

    /////////////////////////////////////////////////// child
    @GetMapping("/child/{id}")
    public AjaxResult showChild(@PathVariable("id") Long id) {
        Optional<WorkflowWaterCleanChildEntity> optional = workflowWaterCleanChildDao.findById(id);
        if(!optional.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_WORK_FLOW_MISSING);
        }

        WorkflowWaterCleanChildEntity houseChildEntity = optional.get();

        houseChildEntity.setPid(houseChildEntity.getWorkflowWaterCleanEntity().getId());

        return AjaxResult.success(houseChildEntity);
    }

    @PostMapping("/child")
    public AjaxResult addChild(@RequestBody WorkflowWaterCleanChildEntity entity) {

        entity.setId(null); // 新增保证 id = null，避免变成更新

        Optional<WorkflowWaterCleanEntity> optionalPainHouse = workflowWaterCleanDao.findById(entity.getPid());
        if(!optionalPainHouse.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_WORK_FLOW_MISSING);
        }

        WorkflowWaterCleanEntity houseEntity = optionalPainHouse.get();

        entity.setWorkflowWaterCleanEntity(houseEntity);
        // 动态计算子
        calcChild(entity);

        WorkflowWaterCleanChildEntity save = workflowWaterCleanChildDao.save(entity);

        return AjaxResult.success(save);
    }

    @PutMapping("/child/{id}")
    public AjaxResult updateChild(@PathVariable("id") Long id, @RequestBody WorkflowWaterCleanChildEntity entity) {

        entity.setId(id); // 新增保证 id = null，避免变成更新

        Optional<WorkflowWaterCleanEntity> optionalPainHouse = workflowWaterCleanDao.findById(entity.getPid());
        if(!optionalPainHouse.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_WORK_FLOW_MISSING);
        }

        WorkflowWaterCleanEntity houseEntity = optionalPainHouse.get();

        entity.setWorkflowWaterCleanEntity(houseEntity);
        // 动态计算子
        calcChild(entity);

        WorkflowWaterCleanChildEntity save = workflowWaterCleanChildDao.save(entity);

        save.setPid(houseEntity.getId());

        return AjaxResult.success(save);
    }

    @DeleteMapping("/child/{id}")
    public AjaxResult deleteChild(@PathVariable("id") Long id) {
        Optional<WorkflowWaterCleanChildEntity> childEntityOptional = workflowWaterCleanChildDao.findById(id);
        if(!childEntityOptional.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_CALIBRATION_MISSION);
        }

        WorkflowWaterCleanChildEntity childEntity = childEntityOptional.get();

        WorkflowWaterCleanEntity workflowPaintHouseEntity = childEntity.getWorkflowWaterCleanEntity();
        workflowPaintHouseEntity.getInner().remove(childEntity);

        workflowWaterCleanDao.save(workflowPaintHouseEntity);


        workflowWaterCleanChildDao.deleteById(id);

        return AjaxResult.success();
    }

    @Deprecated
//    @PostMapping("/child/sync")
    public AjaxResult syncChildPower(@RequestBody WorkflowPowerBody entity) {
        Date startTime = entity.getStartTime();
        Date endTime = entity.getEndTime();
        String mfid = entity.getMfid();
        Set<String> mfids = new HashSet<>();
        mfids.add(mfid);
        Map<String, HttpGetPowerReturnNewBody> powerMapByHourType = httpService2.getPowerListByHourType(mfids, startTime, endTime);

        HttpGetPowerReturnNewBody body = powerMapByHourType.get(mfid);
        Double power = 0.;
        if(ObjectUtils.isNotEmpty(body)) {
            power = body.getSum();
        }

        return AjaxResult.success(power);
    }


    @GetMapping("/child/sync/{id}")
    public AjaxResult syncChildPower(@PathVariable("id") Long id) {
        Optional<WorkflowWaterCleanChildEntity> optional = workflowWaterCleanChildDao.findById(id);
        if(!optional.isPresent()) {
            throw new ServiceException(MessageConstant.ERR_SYNC_WORKFLOW_MISSION);
        }
        WorkflowWaterCleanChildEntity entity = optional.get();
        Date startTime = entity.getStartTime();
        Date endTime = entity.getEndTime();
        String deviceNo = entity.getDevice();
        String mfid = entity.getMfid();
        Set<String> mfids = new HashSet<>();
        mfids.add(mfid);
        Map<String, HttpGetPowerReturnNewBody> powerMapByHourType = httpService2.getPowerListByHourType(mfids, startTime, endTime);

        HttpGetPowerReturnNewBody body = powerMapByHourType.get(mfid);
        double power = 0.;
        if(ObjectUtils.isNotEmpty(body)) {
            power = body.getSum();
        }

        entity.setTotalPower(power);

        WorkflowWaterCleanChildEntity save = workflowWaterCleanChildDao.save(entity);

        return AjaxResult.success(save);

    }

    /////////////////////////////////////////////////  动态计算

    /**
     * 计算动态值
     * @param entity
     * @param shipEntity
     * @param shipRepairEntity
     */

    public static WorkflowWaterCleanEntity dynamicCalc(WorkflowWaterCleanEntity entity,
                                                 ShipEntity shipEntity,
                                                 ShipRepairEntity shipRepairEntity) {

        // 总电量， 子表求和
        List<WorkflowWaterCleanChildEntity> inner = entity.getInner();
        double sum = inner.stream().mapToDouble(t->t.getTotalPower() == null ? 0. : t.getTotalPower()).sum();

        inner.forEach(t->t.setPid(entity.getId()));

        entity.setPowers(sum);

        ///////////////////////////////////////////////////
        entity.setShipName(shipEntity.getName());
        entity.setReporter(shipRepairEntity.getUpdater());
        entity.setShipRepairId(shipRepairEntity.getId());
        return entity;
    }

    private WorkflowWaterCleanChildEntity calcChild(WorkflowWaterCleanChildEntity entity) {

        return entity;
//        try {
//            entity.totalPower = DateUtils.differentDaysDoubleByMillisecond(entity.getStartTime(), entity.getEndTime()) * 24 * entity.getNum() * entity.power;
//        } catch (Exception e) {
//            entity.totalPower = 0.;
//            entity.setPid(entity.getWorkflowPaintHouseEntity().getId());
//        }
//        return entity;
    }
}
